<template>
  <el-dialog
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="cancels"
    :visible.sync="dialog"
    width="900px"
  >
    <!--工具栏-->
    <div class="head-container">
      <el-steps :active="active" finish-status="success">
        <el-step title="选择商品"> </el-step>
        <el-step title="订单"></el-step>
      </el-steps>
      <!-- 搜索 -->
      <el-card v-if="active == 0">
        <el-input
          v-model="query.storeName"
          clearable
          placeholder="输入搜索商品名称"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="toQuery"
        />
        <el-button
          class="filter-item"
          size="mini"
          type="success"
          icon="el-icon-search"
          @click="toQuerys"
          >搜索</el-button
        >
        <el-button
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-info"
          @click="reset"
          >重置</el-button
        >
        <!--表格渲染-->
        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="goods"
          size="small"
          style="width: 100%"
          @selection-change="handleSelectionChanges"
          :row-key="getRowKey" >
          
          <el-table-column
            align="center"
            type="selection"
            width="95"
            :reserve-selection="true"
          >
          </el-table-column>
          <el-table-column label="商品名称" width="150" align="center">
            <template slot-scope="{ row }">
              {{ row.storeName }}
              <p>规格：{{ row.sku }}</p>
            </template>
          </el-table-column>
          <!-- <el-table-column label="商品原价" align="center" prop="otPrice">
        </el-table-column> -->
          <el-table-column label="商品原价" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.price }}￥</span>
            </template>
          </el-table-column>
          <el-table-column label="库存" align="center" width="200px">
            <template  slot-scope="{ row }">
              <!-- <el-button @click="add(row)">＋</el-button> -->
            <span>{{ row.stock }}</span>
            </template>
          </el-table-column>
           <el-table-column label="购买数量" align="center" width="200px" prop="num">
            <template  slot-scope="scope">
              <!-- <el-button @click="add(row)">＋</el-button> -->
              <el-input-number
                v-model="scope.row.num"
                :min="1"
                :max="scope.row.stock"
                style="width: 150px"
              ></el-input-number>
              件
            </template>
          </el-table-column>
          <el-table-column label="商品图片" align="center">
            <template slot-scope="{ row }">
              <img :src="row.image" style="height: 50px" />
            </template>
          </el-table-column>
        </el-table>
             <el-pagination
          :total="total"
          :current-page="page + 1"
          style="margin-top: 8px"
          layout="total, prev, pager, next, sizes"
          :page-sizes="[10, 15, 20, 25,30]"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
        <el-button style="margin-top: 12px" @click="showOrder">订单</el-button>
      </el-card>
      <el-card v-show="active == 1">
             <Detail ref="dto" :is-add="isAdd" @submitFail="fail" />
      </el-card>
    </div>
  </el-dialog>
</template>

<script>
import {
  queryGoods,
  queryBYstore,
  queryRetail,
  queryByCebters,
} from "@/api/yxStoreProduct";
import Detail from "../products/detail";
export default {
  components:{Detail},
  props: {
    isAdd: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      retailId: "",
      order: {},
      member: {
        id: "",
        phone: "",
        retailUser: "",
        address: "",
        name: "",
        userId: "",
      },
      multipleTable: [],
      cardLists: [],
      id: null,
      size: 10,
      total: 0,
      page: 0,
      sort: ["id,desc"],
      goods: [],

      active: 0,
      queryTypeOptions: [
        { key: "orderId", display_name: "礼包" },
        { key: "realName", display_name: "累计" },
        { key: "userPhone", display_name: "普通商品" },
      ],
      query: {
        storeName: "",
      },
      loading: false,
      dialog: false,
      retailId: 0,
      form: {},
      rules: {
        unique: [{ required: true, message: "please enter", trigger: "blur" }],
      },
    };
  },
  created() {
    this.retailId = JSON.parse(localStorage.getItem("SET_USER")).retail;
    this.queryByretailId();
  },
  methods: {
    fail(val){
      //回调
      this.dialog=false
    },
     getRowKey(row){
         return row.id;
    }, 
    resetForm(){
      this.query={}
      this.form = {}
      this.dialog = false
    },
    cancels() {
    this.resetForm();
  },
    reset(){
      if(this.id==-1){
        this.query={}
        this.queryCenters()
      }else{
        this.query={}
        this.selectProduct(this.id);
      }
    },
    getQueryParamess: function () {
      return {
        page: this.page,
        size: this.size,
        sort: this.sort,
        ...this.query,
        ...this.params,
      };
    },

    //查询平台商品信息
    queryCenters() {
      queryByCebters(this.getQueryParamess())
        .then((resp) => {
          // console.log("data===", this.getQueryParamess());
          var list=[]
          list=resp.content;
         list.forEach((item)=>{
            this.$set(item, 'num', 1)
            // item.num=0;
          })
          this.goods = list
          this.total = resp.totalElements;
        })
        .catch((error) => {
          console.log(error);
        });
    },

    //查询登录门店信息
    queryByretailId() {
      const id = this.retailId;
      queryRetail(id)
        .then((resp) => {
          this.member=resp
           this.member.nickname=JSON.parse(localStorage.getItem("SET_USER")).nickName
        })
        .catch((error) => {
          console.log(error);
        });
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1;
    },
    handleChange(value) {},
    handleSelectionChanges(val) {
      this.multipleTable = val;
    },

    getQueryParame: function () {
      return {
        page: this.page,
        size: this.size,
        sort: this.sort,
        ...this.query,
        ...this.params,
        id: this.id,
      };
    },
    getQueryParames: function () {
      return {
        page: this.page,
        sort: this.sort,
        size: this.size,
        ...this.query,
        ...this.params,
        id: this.id,
      };
    },
    toQueryss() {
      debugger
        if(this.id==-1){
          this.selectProduct(this.id);
          
        }else{
           this.queryCenters()
            this.query={}
        }
    },
    toQuerys() {
      if(this.id == -1){
        this.queryCenters();
        this.query={}
      }else{
         queryBYstore(this.getQueryParames())
        .then((resp) => {
          this.goods = resp.content;
          this.total = resp.totalElements;
        })
        this.query={}
        .catch((error) => {
          console.log(error);
        });
      }
    },
    pageChange(e) {
      this.page = e - 1;
      if (this.id === -1) {
        this.queryCenters();
      } else {
        this.selectProduct(this.id);
      }
    }, // 改变每页显示数
    sizeChange(e) {
      this.page = 0;
      this.size = e;

      if (this.id == -1) {
        this.queryCenters();
      } else {
        this.selectProduct(this.id);
      }
    },
    //订单
    showOrder() {
      if (this.multipleTable.length == 0) {
        this.$message({
          showClose: true,
          message: "请先选择商品",
          type: "warning",
        });
        return;
      }
      let totalMoney = 0;
        let totalNum=0
      this.multipleTable.forEach((v) => {
        totalMoney += v.num * v.price;
        totalNum+=v.num
      });
      const _this = this.$refs.dto;
      _this.order={
        statusName: "待支付",
        _status:2,
        status:1,
        type:1,
        buyStoreId:this.retailId,
        uid:this.member.userId,
        storeId:this.id,
        orderId:null,//虚拟单号
        payType: '2',
        shippingType: 1,//快递类型 可选择
        deliverySn: '',//快递名称
        realName: this.member.retailUser,
        userPhone: this.member.phone,
        userAddress: this.member.address,
        mark: "暂无",
        remark: "暂无",
        totalNum:totalNum,
        products: this.multipleTable,
        payPrice: parseInt(totalMoney),
        totalPrice: parseInt(totalMoney),
        payPostage: 0,
        couponPrice: 0,
        deductionPrice: 0.00,//积分折扣
      }
       _this.userDTO = {
        nickname: this.member.nickname,
      };
      this.active = 1;
      this.isAdd=true;
      this.order.type = 1;
      this.order.actualMoney = totalMoney;
    },

    selectProduct(id) {
      this.id = id;
      this.active = 0;
      if (id == -1) {
        this.queryCenters();
      } else {
        queryGoods(this.getQueryParame())
          .then((resp) => {
            var item =[]
            item=resp.content;
           item.forEach((element) => {
            this.$set(element, 'num', 1)
            });
            this.goods = item;
            console.log(this.goods)
            this.total = resp.totalElements;
          })
          .catch((errpr) => {
            console.log(error);
          });
      }
    },
  },

  next() {
    if (this.active++ > 2) this.active = 0;
  },
};
</script>

<style scoped>
.title {
  align-items: center;
}
</style>
